<template>
  <van-address-list
    v-model="AddressId"
    :list="list"
    default-tag-text="默认"
    @add="OnAdd"
    @edit="OnEdit"
    @select="OnSelect"
  />
</template>

<script setup>
// 获取代理
const { proxy } = getCurrentInstance();
// 获取用户信息
const business = proxy.$business;
// 列表响应式数据
const list = ref([]);
// 地址id响应式数据
const AddressId = ref(0);
const action = ref(proxy.$route.query.action ?? "");
// 挂载前钩子
onBeforeMount(() => GetAddressData());
// 获取用户所有的地址数据
const GetAddressData = async () => {
  let params = {
    busid: business.value.id,
  };
  // 发起请求
  let result = await proxy.$http.post({
    url: "/address/index",
    params,
  });
  // 获取数据成功，循环处理数据，按照vant的数据结构处理就可以
  if (result.code === 1) {
    let data = [];
    result.data.forEach((item) => {
      data.push({
        id: item.id,
        name: item.consignee,
        tel: item.mobile,
        address: item.region_text + item.address,
        isDefault: item.status == 1 ? true : false,
      });
      // 默认地址
      if (item.status == 1) {
        AddressId.value = item.id;
      }
    });
    list.value = data;
  }
};
// 新增收货地址，跳转页面
const OnAdd = () => proxy.$router.push("/address/add");
// 编辑
const OnEdit = (item) =>
  proxy.$router.push({ path: "/address/edit", query: { addrid: item.id } });
// 选择
const OnSelect = async (item) => {
  if (action.value === "confirm") {
    // 从确认订单
    const address = {
      id: item.id,
      name: item.name,
      tel: item.tel,
      region_text: item.address,
    };
    // 赋值状态管理器
    proxy.$address.value = address;
    // 返回
    proxy.$router.back();
  } else {
    // 从我的收货地址过来
    // 组装参数
    let params = {
      id: item.id,
      busid: business.value.id,
    };
    // 发起请求
    let result = await proxy.$http.post({
      url: "/address/select",
      params,
    });
    // 处理请求结果
    if (result.code === 1) {
      GetAddressData();
    } else {
      proxy.$fail(result.msg);
    }
  }
};
</script>